/* =============================================================
 * Your Grandmother's guide to Algorithms
 * =============================================================
 *
 * Copyright (c) 2007, Saverio Miroddi
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions are met:
 * 
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright 
 *       notice, this list of conditions and the following disclaimer in the 
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the SaverioMiroddiSoftware nor the names of its 
 *       contributors may be used to endorse or promote products derived from 
 *       this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *  
 * ---------------------------
 * Utils.java
 * ---------------------------
 *
 */
package utils;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class Utils 
{
	/**
	 * I wonder why the **** they don't implement new ArrayList(T...) 
	 */
	public static <T> List<T> asList(T... source)
	{
		List<T> list = new ArrayList<T>();
		for (T t : source) list.add(t);
		return list;
	}
	
	/** 
	 * Split an array in the specified number of arrays.<br>
	 * We must do an amazing mess to implement the generic version 
	 */
	@SuppressWarnings("unchecked")
	public static <T> T[][] split(int numArrays, T... source)
	{
		if (source.length == 0 || numArrays > source.length) 
			throw new IllegalArgumentException();
		
    	Class<? extends Object> objType = source.getClass().getComponentType();
    	// 0 -> we [must] replace the arrays
        T[][] dest = (T[][]) Array.newInstance(objType, numArrays, 0);
        
		/* Split distributing the remainder to the first arrays */

		int unit = source.length / numArrays;
		int remainder = source.length - unit * numArrays;
		
        for (int destIdx = 0, srcIdx = 0; destIdx < dest.length; destIdx++) {
        	int size = unit;
			if (remainder > 0) {
				size++;
				remainder--;
			}
			
			dest[destIdx] = Arrays.copyOfRange(source, srcIdx, srcIdx + size);
        	srcIdx += size;
        }
        
        /* Version using floating point rounding; works for short to reasonably 
         * long numArrays */
        
//		double unit = (double)source.length / numArrays;
//		double currPartial = 0.0;
//		
//        for (int destIdx = 0; destIdx < dest.length; destIdx++) {
//        	double newPartial = currPartial + unit;
//			dest[destIdx] = Arrays.copyOfRange(source, (int)currPartial, (int)newPartial);
//			currPartial = newPartial;
//        }

        return dest;
	}

	/** 
	 * Merge one or more arrays in one.
	 * 
	 * @param the class must be the same for all the source arrays.
	 */
    @SuppressWarnings("unchecked")
	public static <T> T[] merge(T[]... sources) 
	{
		int mergedLen = 0;
		for (T[] source : sources) mergedLen += source.length;
		
    	Class<? extends Object> arrType = sources.getClass().getComponentType();
    	Class<? extends Object> objType = arrType.getComponentType();
        T[] merged = (T[]) Array.newInstance(objType, mergedLen);

		int mergePos = 0;
		
		for (T[] source : sources) {
			System.arraycopy(source, 0, merged, mergePos, source.length);
			mergePos += source.length;
		}
		
		return merged;
	}

    public static class ArrayIterator<T> implements Iterator<T>
    {
    	private final T[] _source;
    	private int _sourcePtr;
    	
    	public ArrayIterator(T[] source, int ptr)
    	{
    		_source = source;
    		_sourcePtr = ptr;
    	}

    	@Override
    	public boolean hasNext()
    	{
    		return _sourcePtr < _source.length;
    	}

    	@Override
    	public T next()
    	{
    		T ret = _source[_sourcePtr];
    		_sourcePtr++;
    		return ret;
    	}

    	@Override
    	public void remove()
    	{
    		throw new UnsupportedOperationException();
    	}
    }
}
